package com.jwater.core.net;

import java.io.Serializable;

import com.jwater.core.common.S;

import jwater.org.apache.mina.core.buffer.IoBuffer;
/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class DataPacket implements Serializable {
	private static final long serialVersionUID = -107187751508319215L;

	private String dataType;
	private byte[] data;

	public byte[] serialize() throws Exception {
		byte[] dataTypeBytes = dataType.getBytes(S.charset);
		IoBuffer ioBuffer = IoBuffer.allocate(8 + dataType.length() + data.length);
		ioBuffer.putInt(dataTypeBytes.length);
		ioBuffer.put(dataTypeBytes);
		ioBuffer.putInt(data.length);
		ioBuffer.put(data);
		return ioBuffer.array();
	}

	public DataPacket deserialize(byte[] data) throws Exception {
		IoBuffer buffer = IoBuffer.wrap(data);
		int len = buffer.getInt();
		byte[] bytes = new byte[len];
		buffer.get(bytes);
		dataType = new String(bytes, 0, bytes.length, S.charset);

		len = buffer.getInt();
		bytes = new byte[len];
		buffer.get(bytes);
		this.data = bytes;
		return this;
	}

	public String getDataType() {
		return dataType;
	}

	public void setDataType(String dataType) {
		this.dataType = dataType;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}
}
